/*****  Category Tree Management Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/***** variables declartion section, begin *****/
var actionState = new ActionState();
var currentActionState = actionState.noaction;
var currentTree = null;
var currentNode = null;
var currentRb   = null;  // for rollback
var maxDepth    = 10;    // limit depth

var ajaxOperationStatus = new AjaxOperationStatus();
// to check the operation status
function AjaxOperationStatus()
{
    this.succ  = "0000";
    this.error = "0001";
}

// the params to transfer to backend
var ajaxParams = new AjaxParams();
function AjaxParams()
{
    this.data_format = "json";
    this.id          = -1;
    this.parent      = -1;
    this.code        = "";
    this.name        = "";
}

// to know the data loaded or not
function ActionState()
{
    this.noaction = 0;
    this.create   = 1;
    this.modify   = 2;
}

/***** variables declartion section, end *****/


/***** init section, begin *****/
$(document).ready(
    function() {
        $('#wacAppBody').unbind('.jeegoocontext');
        initTreeData();
        initTreeNodeDialog();
    //        bindTreeEvents();    // bind the events between functions and components
    }
    );

/***** init section, end *****/


function bindTreeEvents()
{
//    $('#btn_search').bind(
//        'click',
//        function (e)
//        {
//            goSearch();
//        }
//        );
}

function nodeLog(node, treeObj, operator)
{
//    wacDebugLog(operator + ": node code: " + $(node).attr("code") + ": id: " + $(node).attr("id") + ", node_value: " + $(node).attr("node_value")+ ", node_type: " + $(node).attr("node_type"));
//    wacDebugLog(operator + ": parent node code: " + $(treeObj.parent(node)).attr("code") + ": parent: " + $(treeObj.parent(node)).attr("id") + ", node_value: " + $(treeObj.parent(node)).attr("node_value")+ ", node_type: " + $(treeObj.parent(node)).attr("node_type"));
//    wacDebugLog(operator + ": selected node code: " + $(treeObj.selected).attr("code") + ": id: " + $(treeObj.selected).attr("id") + ", node_value: " + $(treeObj.selected).attr("node_value")+ ", node_type: " + $(treeObj.selected).attr("node_type"));

    wacDebugLog(operator + ": node codep: " + $(treeObj.parent(node)).attr("code") + ": parent: " + $(treeObj.parent(node)).attr("id") + ", node_value: " + $(treeObj.parent(node)).attr("node_value")+ ", node_type: " + $(treeObj.parent(node)).attr("node_type"));
}

/*
 * initTreeNodeDialog
 */
function initTreeNodeDialog()
{
    var name = $("#nodeNameA"),
    code = $("#nodeCodeA"),
    allFields = $([]).add(name).add(code),
    tips = $("#validateTips");

    function updateTips(t) {
        tips.text(t).effect("highlight",{},1500);
    }

    function checkDepth(v)
    {
        if ($(currentTree.selected).attr("self_layer") >= v) {
            updateTips("超出本树限制层数!");
            return false;
        } else {
            return true;
        }
    }


    function checkLength(o,n,min,max) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            updateTips("要求输入不少于" + min + " 个字符, 并且不多于" + max + " 个字符");
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o,regexp,n) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    function checkCode(o)
    {
        var flag = true;
        $("div#goodsCategoryTree ul li")
              .filter(function(){
                return this.id.match("node")})
              .each(function(){
                if(o.val()==$(this).attr("code")){
                  flag = false;
                }
//                wacDebugLog(flag + ":" + o.val() + ":" +$(this).attr("code"));
              });

        if(!flag)
        {
            o.addClass('ui-state-error');
            updateTips("已存在相同编码,请另择!");
            return false;
        }
        return flag;
    }

    $("#treeNodeDialog").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 300,
        modal: true,
        buttons: {
            '取消': function() {
                $(this).dialog('close');
            },
            '保存': function() {
                var bValid = true;
                allFields.removeClass('ui-state-error');

                bValid = bValid && checkDepth(maxDepth);
                bValid = bValid && checkLength(name,"name",2,160);
                bValid = bValid && checkLength(code,"code",2,80);
                bValid = bValid && checkRegexp(code,/^[a-z]([0-9a-z_])+$/i,"编码由字母开头,并与 a-z, 0-9, 下划线字符组成!");
                if(currentActionState == actionState.create)
                {
                    bValid = bValid && checkCode(code);
                }
                else  // rename state
                {
                    if(code.val()!= $(currentTree.selected).attr("code"))
                    {
                            bValid = bValid && checkCode(code);
                    }
                }


                if (bValid)
                {
                    if(currentActionState == actionState.create)
                    {
                       var newNode = {"attributes":{"id":-1, "parent":-1, "code":code.val(),"node_value":-1, "node_type":0},"data":{"title":name.val()},"state":"open","children":[]};
                       $.tree.focused().create(newNode, currentTree.selected);
                    }
                    else
                    {
                        if((code.val()!= $(currentTree.selected).attr("code")) || (name.val()!= currentTree.get_text($(currentTree.selected))))
                        {
                            $(currentTree.selected).attr("code", code.val());
                            $.tree.focused().rename(currentTree.selected, name.val());
                        }
                    }
                    $(this).dialog('close');
                }
            }
        },
        open: function(event, ui) {
            updateTips("请输入必填项内容!");
//            wacDebugLog("open1.");
        },
        close: function() {
            allFields.val('').removeClass('ui-state-error');
//            wacDebugLog("close.");
        }
    });

    $("#treeAlertDialog").dialog({
        autoOpen: false,
        bgiframe: true,
        resizable: false,
        height:140,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            '取消': function() {
                $(this).dialog('close');
            },
            '确定': function() {
                $.each(currentTree.selected, function () {
                    currentTree.remove(this);
                });
                $(this).dialog('close');
            }
            
        },
        open: function(event, ui) {
            wacDebugLog("open2.");
        }
    });
}

function initTreeData()
{
    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL+"goodsCategory/getTree",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initTreeDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            // typically only one of textStatus or errorThrown
            // will have info
            wacDebugLog("initTreeData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initTreeDataCallBack(jsonData)
{
//    wacDebugLog($.dump(jsonData));

    $(function () {
        $("#goodsCategoryTree").tree({
            data : {
                type : "json",
                opts : {
                    static : jsonData['items']
                }
            },
            rules : {
                // I have not defined any of these so disabling the checks will save CPU cycles
                use_max_children : false,
                use_max_depth : true
            },
            types : {
                // all node types inherit the "default" node type
                "default" : {
                   draggable	: false,
                   max_children	: -1,
		   max_depth	: (maxDepth-1)
                }
//                "root" : {
//                    draggable : false,
//                    valid_children : [ "folder" ],
//                    icon : {
//                        image : "/images/js_icons/drive.png"
//                    }
//                },
//                "folder" : {
//                    valid_children : [ "folder" ]
//                },
//                "file" : {
//                    // the following three rules basically do the same
//                    valid_children : "none",
//                    max_children : 0,
//                    max_depth :0,
//                    icon : {
//                        image : "/images/js_icons/file.png"
//                    }
//                }
            },
            plugins : {
                contextmenu : {
                    items : {
                        create : {
                            label	: "新建",
                            icon	: "create",
                            visible	: function (NODE, TREE_OBJ) {
                                if(NODE.length != 1) return 0; return TREE_OBJ.check("creatable", NODE);
                            },
                            action	: function (NODE, TREE_OBJ) {
                                currentActionState = actionState.create;
                                $('#treeNodeDialog').dialog('open');
//                                TREE_OBJ.create(false, TREE_OBJ.get_node(NODE[0]));
                            },
                            separator_after : true
                        },
                        rename : {
                            label	: "修改",
                            icon	: "rename",
                            visible	: function (NODE, TREE_OBJ) {
                                if(NODE.length != 1) return false; return TREE_OBJ.check("renameable", NODE);
                            },
                            action	: function (NODE, TREE_OBJ) {
                                currentActionState = actionState.modify;
                                $('#nodeNameA').attr("value", TREE_OBJ.get_text(NODE));
                                $('#nodeCodeA').attr("value", $(NODE).attr("code"));
                                $('#treeNodeDialog').dialog('open');
//                                TREE_OBJ.rename(NODE);
                            }
                        },
                        remove : {
                            label	: "删除",
                            icon	: "remove",
                            visible	: function (NODE, TREE_OBJ) {
                                var ok = true; $.each(NODE, function () {
                                    if(TREE_OBJ.check("deletable", this) == false) ok = false; return false;
                                }); return ok;
                            },
                            action	: function (NODE, TREE_OBJ) {
                                $('#treeAlertDialog').dialog('open');
//                                $.each(NODE, function () {
//                                    TREE_OBJ.remove(this);
//                                });
                            }
                        }
                    }
                }
            },
            callback: {
              oncreate: function(NODE, REF_NODE, TYPE, TREE_OBJ, RB){
                  nodeLog(NODE, TREE_OBJ, "oncreate");
                  currentNode = NODE;
                  currentRb   = RB;

                  ajaxParams.id     = ($(NODE).attr("node_value")==0 || $(NODE).attr("node_value")==-1) ? -1 : $(NODE).attr("node_value");
                  ajaxParams.parent = ($(TREE_OBJ.parent(NODE)).attr("node_value")==undefined) ? -1 : $(TREE_OBJ.parent(NODE)).attr("node_value");
                  ajaxParams.name   = TREE_OBJ.get_text(NODE);
                  ajaxParams.code   = $(NODE).attr("code");

                  createNode(ajaxParams);
              }
              ,
              onrename: function(NODE, TREE_OBJ, RB){
                  nodeLog(NODE, TREE_OBJ, "onrename");
                  currentNode = NODE;
                  currentRb   = RB;

                  ajaxParams.id     = ($(NODE).attr("node_value")==0 || $(NODE).attr("node_value")==-1) ? -1 : $(NODE).attr("node_value");
                  ajaxParams.parent = ($(TREE_OBJ.parent(NODE)).attr("node_value")==undefined) ? "-1" : $(TREE_OBJ.parent(NODE)).attr("node_value");
                  ajaxParams.name   = TREE_OBJ.get_text(NODE);
                  ajaxParams.code   = $(NODE).attr("code");

                  modifyNode(ajaxParams);
              }
              ,
              onsearch : function (NODE, TREE_OBJ) {
                  TREE_OBJ.container.find('.search').removeClass('search');
                  NODE.addClass('search');
                  nodeLog(NODE, TREE_OBJ, "onsearch");
              }
              ,
              onselect: function(NODE, TREE_OBJ){
                  nodeLog(NODE, TREE_OBJ, "onselect");
              }
              ,
              onmove: function(NODE, REF_NODE, TYPE, TREE_OBJ, RB){
                  nodeLog(NODE, TREE_OBJ, "onmove");
              }
              ,
              beforedelete: function(NODE, TREE_OBJ)
              {
                  nodeLog(NODE, TREE_OBJ, "beforedelete");
//                  currentNode = NODE;

                  ajaxParams.id     = ($(NODE).attr("node_value")==0 || $(NODE).attr("node_value")==-1) ? -1 : $(NODE).attr("node_value");
                  ajaxParams.parent = ($(TREE_OBJ.parent(NODE)).attr("node_value")==undefined) ? "-1" : $(TREE_OBJ.parent(NODE)).attr("node_value");
                  ajaxParams.name   = TREE_OBJ.get_text(NODE);
                  ajaxParams.code   = TREE_OBJ.get_text(NODE);
//                  wacDebugLog(ajaxParams);
                  return true;
//                  return false;
              }
              ,
              ondelete: function(NODE, TREE_OBJ, RB) {
                  nodeLog(NODE, TREE_OBJ, "ondelete");
                  deleteNode(ajaxParams);
              }
              ,
              onload: function(TREE_OBJ){
                  currentTree = TREE_OBJ;
//                  wacDebugLog($.dump(jsonData));
              }
              ,
              onsearch : function (n,t) {
//                  t.container.find('.search').removeClass('search');
//                  n.addClass('search');
              }

            }
        });
    });
}

/*
*  invoked by callback function
*/
function setCurrentNodeAttr(jsonData)
{
    $(currentNode).attr("id", jsonData.items.attributes.id);
    $(currentNode).attr("node_value", jsonData.items.attributes.node_value);
    $(currentNode).attr("code", jsonData.items.attributes.code);
    $(currentNode).attr("node_type", jsonData.items.attributes.node_type);
    $(currentNode).attr("parent", jsonData.items.attributes.parent);
}

function createNode(params)
{
    $.ajax({
        url: BASE_URL+"goodsCategory/create",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            createNodeCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("createNode Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function createNodeCallBack(jsonData)
{
   if(jsonData.info.status == ajaxOperationStatus.error)
   {
//       currentTree.remove(currentRb);
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       $(currentTree.parent(currentNode)).attr("node_type", 1);  //be careful in ie8, "type" is keyword that cannot be used
       setCurrentNodeAttr(jsonData);
   }
   currentActionState = actionState.noaction;
//    wacDebugLog($.dump(jsonData));
//    wacDebugLog($(currentNode).dump());
}

function modifyNode(params)
{
    $.ajax({
        url: BASE_URL+"goodsCategory/modify",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            modifyNodeCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("createNode Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function modifyNodeCallBack(jsonData)
{
   if(jsonData.info.status == ajaxOperationStatus.error)
   {
//       currentTree.remove(currentRb);
       wacShowTips(jsonData.info.error_info);
       initTreeData();
   }
   else
   {
       setCurrentNodeAttr(jsonData);
   }
   currentActionState = actionState.noaction;
//    wacDebugLog($.dump(jsonData));
//    wacDebugLog($(currentNode).dump());
}

function deleteNode(params)
{
//    wacDebugLog(params);
    $.ajax({
        url: BASE_URL+"goodsCategory/delete",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            deleteNodeCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("deleteNode Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function deleteNodeCallBack(jsonData)
{
   if(jsonData.info.status == ajaxOperationStatus.error)
   {
       wacShowTips(jsonData.info.error_info);
       initTreeData();
   }
   else
   {
       $(currentTree.selected).attr("node_type", jsonData.items.attributes.node_type);
       nodeLog(currentTree.selected, currentTree, "deleteNodeCallBack");
   }
    
//    wacDebugLog($.dump(jsonData));
//    wacDebugLog($(currentNode).dump());
}